package com.youka.bussiness.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程上下文，线程本地存储，session管理
 */
public class ThreadContextUtil {

    private static ThreadLocal<Map<String, Object>> threadVariableMap = new ThreadLocal() {
    };

    public ThreadContextUtil() {
    }

    /**
     * 获取当前session
     *
     * @return
     */
    private static Map<String, Object> getCurrentThreadContext() {
        Object currentcontext = (Map) threadVariableMap.get();
        if (currentcontext == null) {
            currentcontext = new HashMap();
            threadVariableMap.set((Map<String, Object>) currentcontext);
        }
        return (Map) currentcontext;
    }

    /**
     * 通过key获得session内容
     *
     * @param name
     * @return
     */
    public static Object get(String name) {
        return getCurrentThreadContext().get(name);
    }

    /**
     * 通过key，写入新的session
     *
     * @param name
     * @param value
     */
    public static void put(String name, Object value) {
        getCurrentThreadContext().put(name, value);
    }

    /**
     * 通过key删除session
     *
     * @param name
     * @return
     */
    public static Object remove(String name) {
        Map currentThreadContext = getCurrentThreadContext();
        Object o = currentThreadContext.remove(name);
        if (currentThreadContext.isEmpty()) {
            clear();
        }

        return o;
    }

    /**
     * 清除所有的session
     */
    public static void clear() {
        getCurrentThreadContext().clear();
        threadVariableMap.set(null);
    }


}
